package com.more.spring.boot.springbootmybatisdemo.service.impl;

import com.more.spring.boot.springbootmybatisdemo.mapper.UserMapper;
import com.more.spring.boot.springbootmybatisdemo.pojo.PageResult;
import com.more.spring.boot.springbootmybatisdemo.pojo.User;
import com.more.spring.boot.springbootmybatisdemo.service.UserService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User queryUserById(int id) {
        return userMapper.queryUserById(id);
    }

    @Override
    public List<User> queryUserList() {
        return userMapper.queryUserList();
    }

    /**
     * 分页查询
     *
     * @param currentPage 当前页
     * @param pageSize    每页条数
     * @returnlimitData
     */
    @Override
    public PageResult queryLimitUserList(int currentPage, int pageSize) {

        //计算偏移量
        int offsetData = (currentPage - 1) * pageSize;

        //查询分页数据
        List<User> users = userMapper.queryLimitUserList(pageSize, offsetData);

        //查询数据总条数
        int countData = userMapper.queryDataSize();
        return new PageResult(users, countData);
    }

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    @Override
    public int addNewUser(User user) {
        return userMapper.addNewUser(user);
    }

    /**
     * 根据用户ID删除用户信息
     * @param id
     * @return
     */
    @Override
    public int deleteUserById(int id) {
        return userMapper.deleteUserById(id);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 根据用户名和密码查询用户信息
     * @param user
     * @return
     */
    @Override
    public PageResult queryUserByNameAndGender(User user) {
        List<User> tempUserList = userMapper.queryUserList();
        List<User> userList = null;
        int countData = 0;
        if (StringUtils.isBlank(user.getUname()) && StringUtils.isBlank(user.getGender())) {
            userList = tempUserList;
            countData = tempUserList.size();
        } else {
            userList = tempUserList
                    .stream()
                    .filter(userParam -> (userParam.getUname().equals(user.getUname()) && userParam.getGender().equals(user.getGender())))
                    .collect(Collectors.toList());
            countData =userList.size();
        }
        return new PageResult(userList, countData);
    }
}